// ==================================================
// Programmer:  Jonathan Landrum
// Date:        10 February 2012
// ==================================================
// Program:     sumOfPrimes.cpp
// Purpose:     Adds together the prime numbers less
//              than 2,000,000.
// Assumptions: None.
// ==================================================

#include <iostream>
using namespace std;

// --------------------------------------------------
// Function prototypes
// --------------------------------------------------
bool prime(int);


// --------------------------------------------------
// main():
// Calls the prime() function to determine which
// numbers are prime, and then adds them to the sum.
// --------------------------------------------------
int main () {
	
	// ------------------------------------------
	// Variables
	// ------------------------------------------
	int  counter = 1;
	long sum = 0;
	
	// ------------------------------------------
	// Introduce the program
	// ------------------------------------------
	cout << endl;
	cout << "---------------------------" << endl;
	cout << "-      Sum of Primes      -" << endl;
	cout << "---------------------------" << endl;
	cout << endl;
	cout << "This program adds the prime" << endl;
	cout << "numbers less than 2,000,000" << endl;
	cout << endl;
	
	// ------------------------------------------
	// Main processing loop
	// ------------------------------------------
	while (counter < 2000000) {
		if (prime(counter))
			sum += counter;
		counter += 2;
	} // End while
	
	// ------------------------------------------
	// Return the results
	// ------------------------------------------
	cout << sum << endl;
	cout << "-----------------------------" << endl;
	cout << "\\\\//_ Live long and prosper." << endl;
	return (0);
} // End main


// --------------------------------------------------
// prime():
// Determines if a number is prime
// --------------------------------------------------
bool prime (int n) {
	
	// Variables
	bool result;
	int  i;
	
	// Do work
	if (n <= 1) {
		result = false; // 1 is not prime
		
	} else if ((n == 2) || (n == 3)) {
		result = true; // Hard code 2 and 3
		
	} else if (n % 2 == 0) {
		result = false; // Get rid of evens
		
		/* All other cases are out, so now we check
		 to see if n is divisible by the odd
		 numbers from 3 on. */
	} else {
		i = 3;
		result = true; // Assume it's prime, then prove
		
		while (true) {
			/* If i^2 is not a root of n, or if
			 n % i == 0. (Won't be larger than
			 the square.) */
			if ((i * i > n) || (n % i == 0))
				break;
			i += 2; // Iterate by 2 to get odds
		} // End while
		
		// Record the answer
		if (i * i > n)
			result = true;
		else
			result = false;
	} // End if
	
	
	// Return the answer
	return result;
}